import { ref } from 'vue'
import type { TreeSelectProps, SelectProps } from 'ant-design-vue'
import Api from '@/libs/api'
import type { ApiResponse } from './types'

export const useGoodsBasicInfo = () => {
	const categoryTree = ref<TreeSelectProps['treeData']>([])
	const searchedSuppliers = ref<any[]>([])

	const onLoadCategroyTree = (treeNode: TreeSelectProps['treeData'][number]) => {
		return new Promise<void>(resolve => {
			Api.post('/product/category/select', { pid: treeNode.dataRef.id }).then(
				(res: ApiResponse) => {
					if (res.list) {
						categoryTree.value = categoryTree.value.concat(res.list)
					}
				}
			)
			resolve()
		})
	}

	const supplierSearch = (val: string = '', id: number = 0) => {
		Api.post('/product/supplier/search', { name: val, id: id }).then((res: ApiResponse) => {
			if (res.list) {
				searchedSuppliers.value = res.list
			}
		})
	}

	const initCategoryTree = () => {
		Api.post('/product/category/select', {}).then((res: ApiResponse) => {
			if (res.list) {
				categoryTree.value = res.list
			}
		})
	}

	const initSuppliers = () => {
		Api.post('/product/supplier/search', {}).then((res: ApiResponse) => {
			if (res.list) {
				searchedSuppliers.value = res.list
			}
		})
	}

	return {
		categoryTree,
		searchedSuppliers,
		onLoadCategroyTree,
		supplierSearch,
		initCategoryTree,
		initSuppliers
	}
}
